package com.cac.demo.service.cemopHandoverForm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cac.demo.controller.compressedFiles.CompressedFilesEditor;
import com.cac.demo.dao.cemopHandoverForm.CemopDeliverPlanDao;
import com.cac.demo.dao.materialScan.WmsDeliverPlanDao;
import com.cac.demo.newCode.cemop.dto.CemopZeroCoordinationDTO;
import com.cac.demo.newCode.cemop.service.Impl.CemopServiceImpl;
import com.cac.demo.newCode.interfaceLog.entity.InterfaceLog;
import com.cac.demo.newCode.interfaceLog.service.InterfaceLogService;
import com.cac.demo.newCode.materialStorage.dto.MaterialDTO;
import com.cac.demo.newCode.materialStorage.entity.WmsDeliveryPlan;
import com.cac.demo.newCode.materialStorage.service.IWmsDeliveryPlanService;
import com.cac.demo.newCode.utils.MaterialUtil;
import com.cac.demo.service.materialScan.WmsDeliverPlanService;
import com.cac.demo.service.tsUSer.tsUserImpl.TsUserServiceImpl;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.DateUtil;
import com.cac.demo.util.adapter.DaoException;
import com.cac.demo.util.adapter.ResponseMsg;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class CemopDeliverPlanService {

    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Autowired
    private CemopDeliverPlanDao cemopDeliverPlanDao;
    @Autowired
    private TsUserServiceImpl tsUserService;
    @Autowired
    private WmsDeliverPlanService wmsDeliverPlanService;
    @Resource
    IWmsDeliveryPlanService iwmsDeliveryPlanService;
    @Autowired
    private CompressedFilesEditor compressedFilesEditor;
    @Autowired
    private Environment environment;
    @Resource
    private MaterialUtil materialUtil;
    @Resource
    private CemopServiceImpl cemopServiceImpl;

    @Resource
    private InterfaceLogService interfaceLogService;
    /**
     * Cemop 新增MDS_ITEM表数据
     *
     * Cemop系统交接单新增数据
     * @param json
     * @return
     */
    public int AddCemopMdsItem(JsonNode json) {
        System.out.println("=========================添加MDS_ITEM表===========================");
        if (json == null) {
            throw new IllegalArgumentException("参数为空！");
        }
        int result = 0;
        try {
            HashMap map = new HashMap();
            map.put("MDS_ITEM_ID", (json.has("MTLS_ECD") && !json.get("MTLS_ECD").isNull()) ? json.get("MTLS_ECD").asText() : "");
            map.put("ITEM_CODE", (json.has("DRAW_NO") && !json.get("DRAW_NO").isNull()) ? json.get("DRAW_NO").asText() : "");
            map.put("ITEM_NAME", (json.has("ITEM_NAME") && !json.get("ITEM_NAME").isNull()) ? json.get("ITEM_NAME").asText() : "");
            String itemType = json.get("ITEM_TYPE").asText();
            switch (itemType) {
                case "成品":
                    map.put("ITEM_TYPE", "F");
                    break;
                case "零件":
                    map.put("ITEM_TYPE", "M");
                    break;
                case "标准件":
                    map.put("ITEM_TYPE", "Z");
                    break;
                case "配套成品":
                    map.put("ITEM_TYPE", "F");
                    break;
                case "配套零件":
                    map.put("ITEM_TYPE", "M");
                    break;
                case "零组件":
                    map.put("ITEM_TYPE", "M");
                    break;
                default:
                    // 打印日志
                    log.info("未匹配到符合的物料类型{}", itemType);
                    break;
            }
            map.put("PROD_MODEL", (json.has("PROD_MODEL") && !json.get("PROD_MODEL").isNull()) ? json.get("PROD_MODEL").asText() : "");
            map.put("ATTRIBUTE1","Cemop-101-insertCemop");
            System.out.println("=========================MDS_ITEM表数据==========================="+map);
            result = cemopDeliverPlanDao.AddCemopMdsItem(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }
    /**
     * Cemop预上账功能方法
     */
    public int insertCemopAdvancePosting(JsonNode json) {
        System.out.println("=========================添加交接单表===========================");
        int result = 0;
        try{
            HashMap map = new HashMap();
            map.put("attribute5_desc", (json.has("MDS_ITEM_ID") && !json.get("MDS_ITEM_ID").isNull()) ? json.get("MDS_ITEM_ID").asText() : "");
            map.put("wms_delivery_plan_id", (json.has("MOM_WMS_DELIVERY_PLAN_ID") && !json.get("MOM_WMS_DELIVERY_PLAN_ID").isNull()) ? json.get("MOM_WMS_DELIVERY_PLAN_ID").asText() : "");
            map.put("wms_quality_info_id", (json.has("MOM_WMS_QUALITY_INFO_ID") && !json.get("MOM_WMS_QUALITY_INFO_ID").isNull()) ? json.get("MOM_WMS_QUALITY_INFO_ID").asText() : "");
            map.put("source_type", (json.has("HNDOVR_BLL_SRTP_CD") && !json.get("HNDOVR_BLL_SRTP_CD").isNull()) ? json.get("HNDOVR_BLL_SRTP_CD").asText() : "");
            map.put("delivery_plan_code", (json.has("HNDOVR_BLL_ECD") && !json.get("HNDOVR_BLL_ECD").isNull()) ? json.get("HNDOVR_BLL_ECD").asText() : "");
            map.put("delivery_type", (json.has("HNDOVR_BLL_TYP_CD") && !json.get("HNDOVR_BLL_TYP_CD").isNull()) ? json.get("HNDOVR_BLL_TYP_CD").asText() : "");
            map.put("delivery_status", (json.has("HNDOVR_BLL_STUS_CD") && !json.get("HNDOVR_BLL_STUS_CD").isNull()) ? json.get("HNDOVR_BLL_STUS_CD").asText() : "");
            map.put("product_code", (json.has("MODLS_ECD") && !json.get("MODLS_ECD").isNull()) ? json.get("MODLS_ECD").asText() : "");
            map.put("batch_no", (json.has("BCH_NO") && !json.get("BCH_NO").isNull()) ? json.get("BCH_NO").asText() : "");
            map.put("ao_no", (json.has("AO_ECD") && !json.get("AO_ECD").isNull()) ? json.get("AO_ECD").asText() : "");
            map.put("start_lot_no", (json.has("BEG_SORTIE_NO") && !json.get("BEG_SORTIE_NO").isNull()) ? json.get("BEG_SORTIE_NO").asLong() : 0);
            map.put("end_lot_no", (json.has("EXPIRY_SORTIE_NO") && !json.get("EXPIRY_SORTIE_NO").isNull()) ? json.get("EXPIRY_SORTIE_NO").asLong() : 0);
            map.put("mds_item_id", (json.has("MTLS_ECD") && !json.get("MTLS_ECD").isNull()) ? json.get("MTLS_ECD").asText() : "");
            map.put("item_code", (json.has("DRAW_NO") && !json.get("DRAW_NO").isNull()) ? json.get("DRAW_NO").asText() : "");
            //用于标准件接收叫箱
            map.put("apply_item_code", (json.has("DRAW_NO") && !json.get("DRAW_NO").isNull()) ? json.get("DRAW_NO").asText() : "");
            map.put("quality_code", (json.has("QLTY_ECD") && !json.get("QLTY_ECD").isNull()) ? json.get("QLTY_ECD").asText() : "");
//            map.put("barcode", (json.has("PYSDST_IDNTFC_NO") && !json.get("PYSDST_IDNTFC_NO").isNull()) ? json.get("PYSDST_IDNTFC_NO").asText() : "");
//            if (json.get("PYSDST_IDNTFC_NO").isNull() || json.get("PYSDST_IDNTFC_NO").equals(""))
            JsonNode barcode = json.get("PYSDST_IDNTFC_NO");
            if (barcode == null || barcode.isNull() || barcode.asText().trim().isEmpty())
            {
                map.put("barcode",(json.has("CEFCD_ECD") && !json.get("CEFCD_ECD").isNull()) ? json.get("CEFCD_ECD").asText() : "");
                map.put("ck_barcode",(json.has("CEFCD_ECD") && !json.get("CEFCD_ECD").isNull()) ? json.get("CEFCD_ECD").asText() : "");
            }
            else{
                map.put("barcode", json.get("PYSDST_IDNTFC_NO").asText());
                map.put("ck_barcode", json.get("PYSDST_IDNTFC_NO").asText());
            }
            map.put("delivery_qty", (json.has("DLVR_QTY") && !json.get("DLVR_QTY").isNull()) ? json.get("DLVR_QTY").asDouble() : 0);
            map.put("part_item_qty", (json.has("PART_QTY") && !json.get("PART_QTY").isNull()) ? json.get("PART_QTY").asLong() : 0);
            map.put("item_plane_qty", (json.has("STDALN_NV") && !json.get("STDALN_NV").isNull()) ? json.get("STDALN_NV").asDouble() : 0);
            map.put("parent_item_code", (json.has("FNPRD_PARPCE_NO") && !json.get("FNPRD_PARPCE_NO").isNull()) ? json.get("FNPRD_PARPCE_NO").asText() : "");
            map.put("delivery_emp_code", (json.has("DEVOL_ARTFC_ECD") && !json.get("DEVOL_ARTFC_ECD").isNull()) ? json.get("DEVOL_ARTFC_ECD").asText() : "");
            map.put("delivery_org_code", (json.has("DEVOL_DEPT_ECD") && !json.get("DEVOL_DEPT_ECD").isNull()) ? json.get("DEVOL_DEPT_ECD").asText() : "");
            map.put("delivery_shop", (json.has("DEVOL_BCPLT_ECD") && !json.get("DEVOL_BCPLT_ECD").isNull()) ? json.get("DEVOL_BCPLT_ECD").asText() : "");
            map.put("require_org_code", (json.has("RQM_DEPT_ECD") && !json.get("RQM_DEPT_ECD").isNull()) ? json.get("RQM_DEPT_ECD").asText() : "");
            map.put("require_shop", (json.has("RQM_BCPLT_ECD") && !json.get("RQM_BCPLT_ECD").isNull()) ? json.get("RQM_BCPLT_ECD").asText() : "");
            map.put("require_date", (json.has("RQM_DATE") && !json.get("RQM_DATE").isNull()) ? json.get("RQM_DATE").asText() : "");
            map.put("task_no", (json.has("MISN_NO") && !json.get("MISN_NO").isNull()) ? json.get("MISN_NO").asText() : "");
            map.put("seal_date", (json.has("OILSL_DATE") && !json.get("OILSL_DATE").isNull()) ? json.get("OILSL_DATE").asText() : "");
            map.put("ensure_date", (json.has("GURTEE_DATE") && !json.get("GURTEE_DATE").isNull()) ? json.get("GURTEE_DATE").asText() : "");
            map.put("max_storage_date", (json.has("USE_DATE") && !json.get("USE_DATE").isNull()) ? json.get("USE_DATE").asText() : "");
            map.put("retest_date", (json.has("RETEST_DATE") && !json.get("RETEST_DATE").isNull()) ? json.get("RETEST_DATE").asText() : "");
            map.put("m_agreement_number", (json.has("TECH_AGMTNO_ECD") && !json.get("TECH_AGMTNO_ECD").isNull()) ? json.get("TECH_AGMTNO_ECD").asText() : "");
            map.put("contract_no", (json.has("CRTNO_ECD") && !json.get("CRTNO_ECD").isNull()) ? json.get("CRTNO_ECD").asText() : "");
            map.put("supply_regular_no", (json.has("SUPLR_CEFCD_NO") && !json.get("SUPLR_CEFCD_NO").isNull()) ? json.get("SUPLR_CEFCD_NO").asText() : "");
            map.put("supply_furnace_no", (json.has("PROD_STONO_ECD") && !json.get("PROD_STONO_ECD").isNull()) ? json.get("PROD_STONO_ECD").asText() : "");
            map.put("supply_batch_no", (json.has("PROD_LOTNO_ECD") && !json.get("PROD_LOTNO_ECD").isNull()) ? json.get("PROD_LOTNO_ECD").asText() : "");
            map.put("srm_supply_code", (json.has("SRM_SUPPLY_CODE") && !json.get("SRM_SUPPLY_CODE").isNull()) ? json.get("SRM_SUPPLY_CODE").asText() : "");
            map.put("f_level_no", (json.has("FNPRD_STGE_NO") && !json.get("FNPRD_STGE_NO").isNull()) ? json.get("FNPRD_STGE_NO").asText() : "");
            map.put("f_sequence_no", (json.has("FNPRD_SEQUENCE_NO") && !json.get("FNPRD_SEQUENCE_NO").isNull()) ? json.get("FNPRD_SEQUENCE_NO").asLong() : 0L);
            map.put("route", (json.has("PROCCE_DIVOLBR_ECD") && !json.get("PROCCE_DIVOLBR_ECD").isNull()) ? json.get("PROCCE_DIVOLBR_ECD").asText() : "");
            map.put("remark", (json.has("REMRK_DESC") && !json.get("REMRK_DESC").isNull()) ? json.get("REMRK_DESC").asText() : ""); //备注
            map.put("created_by", (json.has("FOUDR_NO") && !json.get("FOUDR_NO").isNull()) ? json.get("FOUDR_NO").asText() : "");
//        map.put("creation_date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            String formatDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            map.put("creation_date", formatDate);
            map.put("m_product_number", (json.has("PROD_MODEL") && !json.get("PROD_MODEL").isNull()) ? json.get("PROD_MODEL").asText() : "");
            map.put("receive_org_code", (json.has("RCPTN_DEPT_ECD") && !json.get("RCPTN_DEPT_ECD").isNull()) ? json.get("RCPTN_DEPT_ECD").asText() : "");
            map.put("m_parent_number", (json.has("FNPRD_PARPCE_MDL_NAME") && !json.get("FNPRD_PARPCE_MDL_NAME").isNull()) ? json.get("FNPRD_PARPCE_MDL_NAME").asText() : "");
            map.put("substitute_code", (json.has("DLVR_RSVBL_ECD") && !json.get("DLVR_RSVBL_ECD").isNull()) ? json.get("DLVR_RSVBL_ECD").asText() : "");
            map.put("security_level", (json.has("SRTLVL_ECD") && !json.get("SRTLVL_ECD").isNull()) ? json.get("SRTLVL_ECD").asText() : ""); //密级
            map.put("cp_secret_level", (json.has("FNPRD_SRTLVL_ECD") && !json.get("FNPRD_SRTLVL_ECD").isNull()) ? json.get("FNPRD_SRTLVL_ECD").asText() : ""); //成品密级
            map.put("cp_secret_limit_period", (json.has("SECRCY_DL") && !json.get("SECRCY_DL").isNull()) ? json.get("SECRCY_DL").asText() : ""); //保密期限
            map.put("mes_check_qualitication_id", (json.has("CEFCD_ECD") && !json.get("CEFCD_ECD").isNull()) ? json.get("CEFCD_ECD").asText() : "");
            map.put("repart_ass_id", (json.has("ASMBL_DRWNO_ECD") && !json.get("ASMBL_DRWNO_ECD").isNull()) ? json.get("ASMBL_DRWNO_ECD").asText() : "");
            //map.put("func", (json.has("ITEM_TYPE") && !json.get("ITEM_TYPE").isNull()) ? json.get("ITEM_TYPE").asText() : "");
            map.put("ao_barcode", (json.has("AO_ECD") && !json.get("AO_ECD").isNull()) ? json.get("AO_ECD").asText() : "");
            map.put("VERSION", (json.has("VER_ECD") && !json.get("VER_ECD").isNull()) ? json.get("VER_ECD").asText() : "");
            map.put("ATTRIBUTE8_DESC", (json.has("PROCCE_STNO_ECD") && !json.get("PROCCE_STNO_ECD").isNull()) ? json.get("PROCCE_STNO_ECD").asText() : ""); //工艺状态号
            map.put("plan_type", (json.has("PLN_TYP_NO") && !json.get("PLN_TYP_NO").isNull()) ? json.get("PLN_TYP_NO").asText() : ""); //计划类型
//            map.put("ck_barcode", (json.has("MDS_ITEM_ID") && !json.get("MDS_ITEM_ID").isNull()) ? json.get("MDS_ITEM_ID").asText() : "");
            map.put("ATTRIBUTE4","Cemop-101-insertCemop");     //添加Cemop标志
            map.put("ATTRIBUTE9_DESC","SCD_FLG");   //是否扫码（0-非扫码 1-扫码）区分扫码标志
        /*//map.put("wms_item_inventory_id",json.get("==========台账ID=====").asText());
        //map.put("srm_supply_id",json.get("=========成品供应商==========").asText());
        //map.put("m_product_name",json.get("======================成品名称==============").asText());
        //map.put("technical_no",json.get("======================技术协议==============").asText());*/
            System.out.println("=========================交接单表数据==========================="+map);
            result = cemopDeliverPlanDao.insertCemopAdvancePosting(map);
            return result;
        }catch (Exception e)
        {
            log.error("CemopDeliverPlanService.insertCemopAdvancePosting() error:", e);
            return -1;
        }
    }
    /**
     * Cemop 质量信息表
     */
    public int insertCemopWmsQualityInfo(JsonNode json) {
        System.out.println("=========================添加质量信息表===========================");
        int result = 0;
        try {
            HashMap map = new HashMap();
            // 使用三目运算符赋值
            map.put("WMS_QUALITY_INFO_ID", (json.has("MOM_WMS_QUALITY_INFO_ID") && !json.get("MOM_WMS_QUALITY_INFO_ID").isNull()) ? json.get("MOM_WMS_QUALITY_INFO_ID").asText() : "");
            map.put("QUALITY_CODE", (json.has("QLTY_ECD") && !json.get("QLTY_ECD").isNull()) ? json.get("QLTY_ECD").asText() : "");
            map.put("QUALITY_FLAG", (json.has("QLTY_TAG_CD") && !json.get("QLTY_TAG_CD").isNull()) ? json.get("QLTY_TAG_CD").asText() : "");
            map.put("RESERVATION_NOTE_NO", (json.has("MDS_ITEM_ID") && !json.get("MDS_ITEM_ID").isNull()) ? json.get("MDS_ITEM_ID").asText() : "");
            map.put("ABERRATION_NOTE_NO", (json.has("MDS_ITEM_ID") && !json.get("MDS_ITEM_ID").isNull()) ? json.get("MDS_ITEM_ID").asText() : "");
            map.put("USE_LIMIT", (json.has("RESRTD_TAG_CD") && !json.get("RESRTD_TAG_CD").isNull()) ? json.get("RESRTD_TAG_CD").asText() : "");
            map.put("SEAL_DATE", (json.has("OILSL_DATE") && !json.get("OILSL_DATE").isNull()) ? json.get("OILSL_DATE").asText() : "");
            map.put("ENSURE_DATE", (json.has("GURTEE_DATE") && !json.get("GURTEE_DATE").isNull()) ? json.get("GURTEE_DATE").asText() : "");
            map.put("MAX_STORAGE_DATE", (json.has("LNGST_SFKEP_DATE") && !json.get("LNGST_SFKEP_DATE").isNull()) ? json.get("LNGST_SFKEP_DATE").asText() : "");
            map.put("CREATED_BY", (json.has("FOUDR_NO") && !json.get("FOUDR_NO").isNull()) ? json.get("FOUDR_NO").asText() : "");
            String formatDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            map.put("CREATION_DATE", formatDate);
            map.put("CHECK_DATE", (json.has("CHK_DATE") && !json.get("CHK_DATE").isNull()) ? json.get("CHK_DATE").asText() : "");
            map.put("USE_LIMIT_INFO", (json.has("RESRTD_SPCF_DESC") && !json.get("RESRTD_SPCF_DESC").isNull()) ? json.get("RESRTD_SPCF_DESC").asText() : "");   //限用说明
            map.put("X_PRODUCT_CODE", (json.has("RESRTD_MODLS_ECD") && !json.get("RESRTD_MODLS_ECD").isNull()) ? json.get("RESRTD_MODLS_ECD").asText() : "");   //限用机型
            map.put("X_LIMIT_BATCH_NO", (json.has("RESRTD_BCH_NO") && !json.get("RESRTD_BCH_NO").isNull()) ? json.get("RESRTD_BCH_NO").asText() : "");          //限用批次
            map.put("X_LIMIT_LOT_NO", (json.has("RESRTD_SORTIE_NO") && !json.get("RESRTD_SORTIE_NO").isNull()) ? json.get("RESRTD_SORTIE_NO").asText() : "");   //限用架次
            map.put("RETEST_DATE", (json.has("RETEST_DATE") && !json.get("RETEST_DATE").isNull()) ? json.get("RETEST_DATE").asText() : "");                     //复试期
            map.put("MES_CHECK_QUALITICATION_ID", (json.has("CEFCD_ECD") && !json.get("CEFCD_ECD").isNull()) ? json.get("CEFCD_ECD").asText() : "");

            map.put("ATTRIBUTE1","Cemop-101-insertCemop");
            /*//map.put("QUALITY_NOTE_NO","=======================审理单、单据号=========================");
//            map.put("SEAL_STATUE","油封状态/封存状态");
//            map.put("TEST_CYCLE","定试周期");
//            map.put("CHECK_USER","验收人");
//            map.put("CHECK_RESULT","检验结论");
//            map.put("IS_ARMY","是否军检");
//            map.put("MAKE_DATE","到货日期");
//            map.put("OUT_FACTORY_DATE","出厂日期");
//            map.put("UNSEAL_DATE","启封日期");
//            map.put("NEXT_SEAL_DATE","下次油封日期");
//            map.put("NEXT_RETEST_DATE","下次定试日期；（材料、成品）");
//            map.put("STORAGE_DATE","库存期；（材料、成品）");
//            map.put("FIRST_OVERHAUL_DATE","成品首翻期；成品首次翻修期；（成品）");
//            map.put("MAX_USED_DATE","使用寿命期/总寿命器；不可翻修的成品为使用寿命期，可翻修的成品为总寿命期；（成品）");
//            map.put("LAST_FIX_DATE","返修/超处日期");
//
//            map.put("xLimitLotNo",json.get("MDS_ITEM_ID").asText());*/

            System.out.println("=========================质量表数据==========================="+map);
            //yebo 新增判断，校验质量表是否存在数据，存在不写入数据
            int cnt = wmsDeliverPlanDao.queryQualityIsExists(map);
            if (cnt == 0) {
                result = cemopDeliverPlanDao.insertCemopWmsQualityInfo(map);
            } else {
                log.info(">>>>>>>>>>>>>>>质量表数据已经存在，更新部分字段>>>>>>>>>>>>>>>" + map.toString());
                wmsDeliverPlanDao.updateWmsQualityInfo(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }


    /**
     * Cemop 扫码移交-判断合格证号是否重复
     */
    public boolean queryPartHgzIsRepeat(String barcode,String shop){
        int count = cemopDeliverPlanDao.queryPartHgzIsRepeat(barcode,shop);
        if(count>1){
            return true;
        }
        return false;
    }
    /**
     * 通过条码判断物料所属系统
     * @param barcode
     * @return
     */
    public String getSystemByBarcode(String barcode){
        String system = cemopDeliverPlanDao.getSystemByBarcode(barcode);
        System.out.println("================system数据来源系统============="+barcode+"="+system);
        return system;
   }
    /**
     * 通过协调单id判断物料所属系统
     * @param wmsDeliveryCoordinateId
     * @return
     */
    public String getSystemByCoordinateId(String wmsDeliveryCoordinateId){
        String system = cemopDeliverPlanDao.getSystemByCoordinateId(wmsDeliveryCoordinateId);
        System.out.println("================协调单数据来源系统============="+wmsDeliveryCoordinateId+"="+system);
        return system;
    }

    /**
     * 通过条码判断物料所属系统 扫码退回
     * @param barcode
     * @return
     */
    public String getScenBackSystemByBarcode(String barcode){
        String system = cemopDeliverPlanDao.getScenBackSystemByBarcode(barcode);
        System.out.println("================system数据来源系统============="+barcode+"="+system);
        return system;
    }
    /**
     * 通过交接单id判断物料所属系统
     * @param wmsDeliveryPlanId
     * @return
     */
    public String getSystemByid(String wmsDeliveryPlanId){
        String system = cemopDeliverPlanDao.getSystemByid(wmsDeliveryPlanId);
        System.out.println("================system数据来源系统============="+wmsDeliveryPlanId+"="+system);
        return system;
    }
    /**
     * 物料扫码移交接口
     * @param map
     * @return
     */
    @Transactional
    public ResponseMsg<String> changeTransferCemop(@RequestBody Map map) throws ParseException {
        String str =map.get("barcode").toString();
        String[] parts = str.split("\\*");
        String s = parts[0];
        MaterialDTO materialDTO = materialUtil.getMaterialDTO(s);
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        //条码
        String barCode = (String) materialDTO.getBarCode();
        //扫码人工号
        String userCode = (String) map.get("userCode");
        //扫码物料类型
        String barcodeType = (String) map.get("barcodeType");//值为 CP,LJ,BJ
        //扫码
        String bzjCodeType = (String) map.get("bzjCodeType");//值为BZJCK   BZJCKAO

        //yebo 2023-08-18 新增校验扫码人工号是否正确
        responseMsg = wmsDeliverPlanService.searchWorkerCode(userCode);
        if("201".equals(responseMsg.getRetCode())){
            return responseMsg;
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = (String) request.getSession().getAttribute("account");
        String msgId = CreatMsgId.getMsgId();
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        if (Objects.isNull(userId)) {
            log.info("session过期，请重新登陆");
            responseMsg.setErrorDesc("账户已过期，请重新登录").setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(userId)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户").setMessage("管理员账号无法完成操作，请切换登录用户");
        }
        log.info("IP" + IP);
        //事务管理
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        String shop = (String)tsUserService.getUserInfoByAccount(userId).get("shop");

        try {
            //零件
            if ("M".equals(materialDTO.getMaterialType())) {
                //判断当前零件的条码对应的合格证号是否重复
                responseMsg = changeMaterialSate(barCode, IP, userCode,userId);
                if ("200".equals(responseMsg.getRetCode())) {
                    responseMsg.setRetCode("200").setMessage("操作成功！");
                }
                if(queryPartHgzIsRepeat(barCode,shop)){
                    responseMsg.setRetCode("200").setMessage(barCode+"条码合格证号存在重复，请确认交接单是否重复").setErrorDesc(barCode+"条码合格证号存在重复，请确认交接单是否重复");
                }
            } else if ("F".equals(materialDTO.getMaterialType())) {//成品
                //判断是否存在该核格证号的成品
                responseMsg = changeMaterialSateCP(barCode, IP, userCode,userId);
                if ("200".equals(responseMsg.getRetCode())) {
                    if (responseMsg.getMessage().length() > 10) {
                        responseMsg.setMessage(responseMsg.getMessage());
                    } else {
                        responseMsg.setRetCode("200").setMessage("操作成功！");
                    }
                }
            }
            else{
                String cemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
                if (parts.length>1)
                {
                    LambdaQueryWrapper<WmsDeliveryPlan> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsDeliveryPlan::getAoNo, parts[0]);
                    queryWrapper.eq(WmsDeliveryPlan::getProductCode, parts[1]);
                    queryWrapper.eq(WmsDeliveryPlan::getBatchNo, parts[2]);
                    queryWrapper.eq(WmsDeliveryPlan::getStartLotNo, parts[3]);
                    List<WmsDeliveryPlan> wmsDeliveryPlans = iwmsDeliveryPlanService.list(queryWrapper);
                    for (WmsDeliveryPlan wmsDeliveryPlan : wmsDeliveryPlans)
                    {
                        wmsDeliveryPlan.setDeliveryStatus("2");
                        wmsDeliveryPlan.setDeliveryEmpCode(userCode);
                        wmsDeliveryPlan.setDeliveryDate(new Date());
                        wmsDeliveryPlan.setLastUpdateDate(new Date());
                        iwmsDeliveryPlanService.updateById(wmsDeliveryPlan);
                        //打包数据发送到Cemop
                        String result= changeTransferCemop0407(wmsDeliveryPlan.getWmsDeliveryPlanId(),IP,userCode,wmsDeliveryPlan.getBarcode(),userId,cemopUrl);
                    }
                    responseMsg.setRetCode("200").setMessage("操作成功！");
                }
                else{
                    responseMsg = wmsDeliverPlanService.changeMaterialSateBJ(barCode, IP, userCode);
                    if ("200".equals(responseMsg.getRetCode())) {
                        responseMsg.setRetCode("200").setMessage("操作成功！");
                        //yebo 2023-08-05标准件不针对某本ao，针对具体的某个物料来移交
                        //查询此AO下要移交的AO
                        List<HashMap> deliveryPlans = wmsDeliverPlanDao.queryBzjInfo(barCode);
                        for (HashMap deliveryPlan : deliveryPlans) {
                            //打包数据发送到Cemop
                            String result= changeTransferCemop0407((String) deliveryPlan.get("wmsDeliveryPlanId"),IP,userCode,(String) deliveryPlan.get("barcode"),userId,cemopUrl);
                        }
                    }
                }
            }

            if ("201".equals(responseMsg.getRetCode())) {
                //判断当前交接单是已移交还是未上账
                int c = wmsDeliverPlanService.searchDeliveryPlanExists(barCode);
                if (c == 0) {
                    responseMsg.setRetCode("201").setMessage("条码号为：" + barCode + "未预上账！请确认").setErrorDesc("条码号为：" + barCode + "未预上账！请确认");
                } else {
                    responseMsg.setRetCode("201").setMessage("条码号为：" + barCode + "已经移交！").setErrorDesc("条码号为：" + barCode + "已经移交！");
                }
                //全部成功提交事务
                platformTransactionManager.rollback(transaction);
            } else {
                //全部成功提交事务
                platformTransactionManager.commit(transaction);
            }
        } catch (Exception e) {
            //有一个失败，回滚事务
            e.printStackTrace();
            platformTransactionManager.rollback(transaction);
            responseMsg.setMessage(e.getMessage()).setRetCode("201");
        } finally {
            return responseMsg;
        }
    }
    /**
     * 根据前端按钮修改接收物料状态（零件）
     *
     * @param barcode
     * @param //funcType transfer：移交 acc：接收 reject：拒收
     * @return
     */
    @Transactional
    public ResponseMsg changeMaterialSate(String barcode, String IP, String userCode,String userId) throws ParseException {
        ResponseMsg responseMsg = new ResponseMsg();
        //首要判断，判断交接单是否存在
        Integer exist = cemopDeliverPlanDao.searchByBarCodeCemop(barcode);
        try {
            //判断当前扫码人是否与交接单单位一致

            //是否存在需要处理的条码，exist为0时，说明当前没有需要处理的交接单
            if (exist == 0) {
                responseMsg.setRetCode("201");
            } else {
                System.out.println(DateUtil.nowTime());
                //获取要修改的交接单id
                List<String> ids = cemopDeliverPlanDao.getIdByBarcode(barcode);
                for (String id:ids){
                    Integer count = cemopDeliverPlanDao.changeTransferTypeCemop(id, DateUtil.nowTime(), IP, userCode);
                    //打包数据发送到Cemop
                    if (count>0)
                    {
                        String cemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
                        changeTransferCemop0407(id,IP,userCode,barcode,userId,cemopUrl);
                        //添加日志-0407
//                        JSONObject jsonObject = new JSONObject();
//                        jsonObject.put("wmsDeliveryPlanId", id);
//                        jsonObject.put("barcode", barcode);
//                        interfaceLogService.saveInterfaceLog("零件扫码移交", cemopUrl, jsonObject, result, IP,"changeMaterialSate");
                    }
                }
                responseMsg.setRetCode("200");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseMsg.setRetCode("201");
            throw new DaoException(e.getMessage());

        } finally {
            return responseMsg;
        }
    }

    /**
     * 成品物料进行接收 Cemop
     * @param barcode
     * @return
     */
    @Transactional
    public ResponseMsg changeMaterialSateCP(String barcode, String IP, String userCode,String userId) {
        ResponseMsg responseMsg = new ResponseMsg();
        //首要判断，是否物流信息存在，并且协调单状态是否为已归零
        Integer exist = wmsDeliverPlanDao.searchByMesCheckQualiticationId(barcode);
        String result = null;
        try {
            //条码是否存在
            if (exist > 0) {
                //判断当前合格证是否拆分
                int index = barcode.indexOf("/");
                String qualification = "";
                //拆分过
                if (index > 1) {
                    qualification = barcode.substring(0, index);
                    //查询相同合格证条码
                    List<HashMap> plans = cemopDeliverPlanDao.selectCemopCPIds(qualification);
                    //存在未移交相同合格证
                    if (plans.size() > 0) {
                        //将相同合格证且状态为1的条码改为2
                        for (HashMap<String,String> plan : plans) {
                            String id = plan.get("WMS_DELIVERY_PLAN_ID");
                            String barcodes = plan.get("BARCODE");
                            cemopDeliverPlanDao.changeCemopTransferTypeById(id, DateUtil.nowTime(), IP, userCode);
                            //打包数据发送到Cemop
                            String cemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
                            String result2=changeTransferCemop0407(id,IP,userCode,barcodes,userId,cemopUrl);
                            //添加日志-0407
//                            JSONObject jsonObject = new JSONObject();
//                            jsonObject.put("wmsDeliveryPlanId", id);
//                            jsonObject.put("barcode", barcodes);
//                            interfaceLogService.saveInterfaceLog("成品扫码移交", cemopUrl, jsonObject, result2, IP,"changeMaterialSateCP");
                            responseMsg.setRetCode("200").setMessage("扫码成功");
                        }
                    }
                }//未拆分过
                else {
                    //查询相同合格证条码
                    List<String> ids = cemopDeliverPlanDao.selectCemopCPId(barcode);
                    //打包数据发送到Cemop
                    String cemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
                    if ("admin".equals(userCode)) {
                        responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
                    }
                    cemopDeliverPlanDao.changeCemopTransferTypeById(ids.get(0), DateUtil.nowTime(), IP, userCode);
                    String result3 = changeTransferCemop0407(ids.get(0),IP,userCode,barcode,userId,cemopUrl);
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("wmsDeliveryPlanId", ids.get(0));
//                    jsonObject.put("barcode", barcode);
//                    interfaceLogService.saveInterfaceLog("成品扫码移交", cemopUrl, jsonObject, result3, IP,"changeMaterialSateCP");
                    responseMsg.setRetCode("200").setMessage("移交成功！");

                }
            } else {
                responseMsg.setRetCode("201");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return responseMsg;
        }
    }

    //扫码退回 Cemop
    public ResponseMsg<String> cemopScenBack(@RequestBody Map map)
    {
        String str =map.get("barcode").toString();
        String[] parts = str.split("\\*");
        String code = parts[0];
        MaterialDTO materialDTO = materialUtil.getMaterialDTO(code);
//        MaterialDTO materialDTO = materialUtil.getMaterialDTO(map.get("barcode").toString());
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String barcode = (String) materialDTO.getBarCode();
        String returnReason = (String) map.get("returnReason");
        String rejectReason="";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = (String) request.getSession().getAttribute("account");
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        log.info("IP" + IP);
        if (Objects.isNull(userId)) {
            log.info("session过期，请重新登陆");
            responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(userId)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
//        String barcodeType = (String) map.get("barcodeType");
        String barcodeType = (String) materialDTO.getMaterialType();
        String bzjCodeType = (String) map.get("bzjCodeType");

        List<String> wmsDeliverPlanIds = new ArrayList<>();
        //扫码人工号
        String userCode = (String) map.get("userCode");
        //不是标准件，成品零件一次只有一个，直接退
        if (!"Z".equals(barcodeType)) {
            //yebo 新增获取当前退回条码的主键
            wmsDeliverPlanIds = wmsDeliverPlanService.getScanBarcodeWmsDeliverPlanId(barcode);
            if(wmsDeliverPlanIds != null && wmsDeliverPlanIds.size() == 0){
                return responseMsg.setMessage("未发起协调或协调单未提交！").setRetCode("201");
            }
            //yebo 2023-04-06 判断是否发起协调,以及单位是否一致
            for (String s : wmsDeliverPlanIds) {
                responseMsg = wmsDeliverPlanService.checkCoordinate(s, userCode, userId);
                if ("201".equals(responseMsg.getRetCode())) {
                    return responseMsg;
                }
            }
        } else {
            if (parts.length>1)
            {
                wmsDeliverPlanIds = wmsDeliverPlanDao.searchBzjWmsAo(parts[0],parts[1],parts[2],parts[3]);
            }
            else {
                wmsDeliverPlanIds = wmsDeliverPlanDao.searchBzjWmsId(barcode);
            }
        }

        //事务管理
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            Integer isSucceed = 0;
            if (parts.length>1 || materialDTO.getMaterialType().equals("Z")) {
                isSucceed = wmsDeliverPlanService.changeReturnTypeBzj(wmsDeliverPlanIds, barcode, returnReason, userId, userCode);
            } else {
                isSucceed = wmsDeliverPlanService.changeReturnTypeLjCP(wmsDeliverPlanIds, barcode, returnReason, userId, userCode);
            }

            log.info("isSucceed" + isSucceed);
            if (isSucceed != 0) {
                for (String wmsDeliverPlanId : wmsDeliverPlanIds) {
                    responseMsg.setRetCode("200").setMessage("退回成功");
                    //传回Cemop系统的参数
                    ObjectMapper mapper = new ObjectMapper();
                    List<JSONObject> list = new ArrayList<>();
                    JSONObject json = new JSONObject();
                    json.put("momWmsDeliveryPlanId", wmsDeliverPlanId);  //交接单id
                    json.put("rejectReason", returnReason);              //退回原因
                    json.put("userId", userId);               //移交人工号
                    list.add(json);
                    long beginTime = System.currentTimeMillis();
                    log.info("======开始时间=======" + beginTime);
                    String zipUrl =compressedFilesEditor.generateZip(mapper.writeValueAsString(list));
                    String CemopUrl = environment.getProperty("cemopUrl.rejectPlan");
                    compressedFilesEditor.fileSend(list,zipUrl, CemopUrl,"扫码退回");
                    long endTime = System.currentTimeMillis();
                    log.info("======消耗时间=======" + (endTime - beginTime) + "ms");

                    //协调单归零后通知Cemop
                    CemopZeroCoordinationDTO cemopZeroCoordinationDTO = new CemopZeroCoordinationDTO();
                    String wmsDeliveryCoordinateId = wmsDeliverPlanService.getCoordinate(wmsDeliverPlanId);
                    cemopZeroCoordinationDTO.setMomWmsDeliveryCoordinateId(wmsDeliveryCoordinateId);
                    cemopZeroCoordinationDTO.setUserId(userId);
                    cemopServiceImpl.sendZeroCoordinationData(cemopZeroCoordinationDTO);
                }
            } else responseMsg.setRetCode("201").setErrorDesc("退回失败！");
            //全部成功提交事务
            platformTransactionManager.commit(transaction);
        } catch (Exception e) {
            //有一个失败，回滚事务
            e.printStackTrace();
            platformTransactionManager.rollback(transaction);
            responseMsg.setMessage(e.getMessage()).setRetCode("201");
        } finally {
            return responseMsg;
        }
    }
    //零件成品扫码移交数据打包
    public void changeTransferCemop(String id, String IP,String userCode,String barcode,String userId)
    {
        String CemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
        String logisticscode = environment.getProperty("cemopinfo.logisticscode");
        String logisticsName = environment.getProperty("cemopinfo.logisticsName");
        //定义json对象存储数据，打包发送到Cemop
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        String shop = cemopDeliverPlanDao.getShopByid(id).get(0);
        json.put("momWmsDeliveryPlanId", id);  //交接单id
        json.put("logisticscode", logisticscode);  //物流区域编码
        json.put("logisticsName", logisticsName);      //物流区域名称
        json.put("empCode", userCode);      //移交人工号
        json.put("userId", userId);               //操作人工号
        json.put("shop", shop);      //shop
        json.put("barCode", barcode);      //barcode
        jsonArray.add(json);
        System.out.println("==================零件成品扫码移交数据================:"+jsonArray.toString());
        String path = compressedFilesEditor.generateZip(jsonArray.toString()); //将json转换为zip文件 url
        compressedFilesEditor.fileSend(jsonArray.toString(),path, CemopUrl,"扫码移交");
    }

    public String changeTransferCemop0407(String id, String IP,String userCode,String barcode,String userId,String cemopUrl)
    {
        String CemopUrl = environment.getProperty("cemopUrl.deliveryPlan");
        String logisticscode = environment.getProperty("cemopinfo.logisticscode");
        String logisticsName = environment.getProperty("cemopinfo.logisticsName");
        //定义json对象存储数据，打包发送到Cemop
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        String shop = cemopDeliverPlanDao.getShopByid(id).get(0);
        json.put("momWmsDeliveryPlanId", id);  //交接单id
        json.put("logisticscode", logisticscode);  //物流区域编码
        json.put("logisticsName", logisticsName);      //物流区域名称
        json.put("empCode", userCode);      //移交人工号
        json.put("userId", userId);               //操作人工号
        json.put("shop", shop);      //shop
        json.put("barCode", barcode);      //barcode
        jsonArray.add(json);
        System.out.println("==================零件成品扫码移交数据================:"+jsonArray.toString());
        String path = compressedFilesEditor.generateZip(jsonArray.toString()); //将json转换为zip文件 url
        compressedFilesEditor.fileSend(jsonArray.toString(),path, CemopUrl,"扫码移交");
        return null;
    }
}
